import { forwardRef, useImperativeHandle, useState, memo, useMemo, useEffect, useRef } from 'react'
import { Button, message } from 'antd'
import { DeleteOutlined } from '@ant-design/icons'
import LdPrintTable from '../../../../components/LdPrintTable'
import './index.scss'
import bus from '../../../../utils/eventBus'
const AddFile = forwardRef((props: any, ref: any) => {
    const { diskType = 1 } = props
    const [fileList, setFileList] = useState<any[]>([])
    const uploadSuccess = useRef<any[]>([])
    const columns = useRef<any[]>([
        {
            key: 'img',
            dataIndex: 'img',
            title: '图标',
            width: 50,
            render: (_: any, record: any) => {
                return (
                    <img src={getIcon(record.suffix)} style={{
                        display: 'flex',
                        width: '22px',
                        height: '22px',
                        cursor: 'pointer',
                        objectFit: 'contain'
                    }} draggable={false} alt="" />
                )
            }
        },
        {
            title: '标题',
            key: 'title',
            dataIndex: 'title',
            ellipsis: true
        },
        {
            title: '大小',
            key: "size",
            dataIndex: 'size',
            width: 100,
            render: (_: any, record: any) => {
                return (
                    <div className="text-name">
                        {getSizeView(record.size)}
                    </div>
                )
            }
        },
        {
            title: '类型',
            key: 'type',
            dataIndex: 'type',
            width: 70,
            render: (_: any, record: any) => {
                return (
                    <div className="text-name">
                        {record.suffix}
                    </div>
                )
            }
        },
        {
            dataIndex: 'action',
            key: 'action',
            title: '操作',
            width: 50,
            render: (_: any, record: any) => {
                return (
                    <span style={{ width: '15px', height: '18px', cursor: 'pointer', color: 'red' }}
                        onClick={() => handleDelete(record)}>
                        <DeleteOutlined />
                    </span>
                )
            }
        }
    ])
    const compareFileSize = (size1: string, size2: string) => {
        // 定义单位之间的转换关系
        const units: any = {
            B: 1,
            K: 1,
            M: 1024,
            G: 1024 * 1024,
            T: 1024 * 1024 * 1024,
        };
        // 提取单位和数值
        const parseSize = (str: string) => {
            const match = str.match(/^(\d+(\.\d+)?)\s*([KMGT]?)B?$/i);
            if (!match) {
                throw new Error("Invalid file size format: " + str);
            }
            const value = parseFloat(match[1]);
            const unit = match[3].toUpperCase() ? match[3].toUpperCase() : "B";
            if (!units.hasOwnProperty(unit)) {
                throw new Error("Invalid file size unit: " + unit);
            }
            return value * units[unit];
        };
        // 转换字符串为比较用的数值
        const sizeValue1 = parseSize(size1);
        const sizeValue2 = parseSize(size2);
        return sizeValue1 < sizeValue2;
    }
    const fileLimit = useMemo(() => {
        if (diskType === 1) {
            return "650M";
        } else {
            return "4.3G";
        }
    }, [diskType])
    const getSizeView = (size: number): string => {
        if (!size) return "0K";
        const num = 1024.0;
        if (size < num) {
            return `${size}B`;
        }
        if (size < Math.pow(num, 2)) {
            return `${(size / num).toFixed(2)}K`;
        }
        if (size < Math.pow(num, 3)) {
            return `${(size / Math.pow(num, 2)).toFixed(2)}M`;
        }
        if (size < Math.pow(num, 4)) {
            return `${(size / Math.pow(num, 3)).toFixed(2)}G`;
        }
        return `${(size / Math.pow(num, 4)).toFixed(2)}T`;
    }
    const totalSize = useMemo(() => {
        const total = fileList.reduce((pre, newValue) => {
            return pre + newValue.size;
        }, 0);
        if (total === 0) {
            return "0K";
        }
        return getSizeView(total);
    }, [fileList])
    const sizeColor = useMemo(() => {
        return compareFileSize(totalSize, fileLimit) ? "#0b7cf1" : "#FF2222";
    }, [fileList])
    const totalSizeUnit = useMemo(() => {
        const total = fileList.reduce((pre: number, newValue: any) => {
            return pre + newValue.size;
        }, 0);
        return total
    }, [fileList])
    const getIcon = (icon: string) => {
        if (icon === "doc") {
            return require("../../../../assets/file-icon/doc.png");
        } else if (icon === "docx") {
            return require("../../../../assets/file-icon/doc.png");
        } else if (icon === "jpg") {
            return require("../../../../assets/file-icon/jpg.png");
        } else if (icon === "png") {
            return require("../../../../assets/file-icon/png.png");
        } else if (icon === "pdf") {
            return require("../../../../assets/file-icon/pdf.png");
        } else if (icon === "tiff") {
            return require("../../../../assets/file-icon/tiff.png");
        } else if (icon === "txt") {
            return require("../../../../assets/file-icon/txt.png");
        } else if (icon === "xsl") {
            return require("../../../../assets/file-icon/xsl.png");
        } else if (icon === "rtf") {
            return require("../../../../assets/file-icon/rtf.png");
        } else {
            return require("../../../../assets/file-icon/default.png");
        }
    }
    const handleAddFile = () => {
        window.chromePro.addBurnFilesNt(JSON.stringify({ window: "刻录光盘" }));
    }
    const handleAddFolder = () => {
        window.chromePro.addBurnDirNt(JSON.stringify({ window: "刻录光盘" }));
    }
    const addBurnDirInfoNtFinished = (res: any) => {
        setFileList(origin => {
            const index = origin.findIndex((k) => k.path === res.data.path);
            if (index < 0) {
                origin.unshift({ ...res.data, percent: 0, suffix: "文件夹" });
            }
            return [...origin]
        })
    }
    const addBurnFilesInfoNtFinished = (res: any) => {
        setFileList(origin => {
            res.data.forEach((item: any) => {
                const file = origin.find((k) => k.path === item.path);
                if (!file) {
                    origin.unshift({
                        ...item,
                        percent: 0,
                    });
                } else {
                    message.warning('文件重复添加')
                }
            });
            return [...origin]
        })
    }
    const handleAllDelete = () => {
        setFileList([])
    }
    const addFilesFinished = (res: any) => {
        uploadSuccess.current = [...uploadSuccess.current, res.data]
    }
    const getBurnFolderProgress = (res: any) => {
        const data = [...fileList]
        const item = data.find((f) => f.uid === res.data.uid);
        if (item) {
            item.percent = res.data.process;
        }
        setFileList(data)
    }
    const addFolderFinished = (res: any) => {
        uploadSuccess.current = [...uploadSuccess.current, res.data]
    }
    const handleDelete = (file: any) => {
        setFileList(origin => {
            return origin.filter((k) => k.uid !== file.uid)
        })
        uploadSuccess.current = uploadSuccess.current.filter((v) => v.uid !== file.uid);
    }
    const fileCount = () => {
        return fileList.length;
    }
    const checkIsUploadSuccess = () => {
        if (!compareFileSize(totalSize, fileLimit)) {
            return { success: false, message: "文件大小已超过限制!" };
        }
        return { success: true, fileList: fileList };
    }
    useEffect(() => {
        bus.addListener('addBurnDirInfoNtFinished', addBurnDirInfoNtFinished)
        bus.addListener('addBurnFilesInfoNtFinished', addBurnFilesInfoNtFinished)
    }, [])
    useEffect(() => {
        return () => {
            bus.removeListener('addBurnDirInfoNtFinished', addBurnDirInfoNtFinished)
            bus.removeListener('addBurnFilesInfoNtFinished', addBurnFilesInfoNtFinished)
        }
    }, [])
    useImperativeHandle(ref, () => ({
        fileCount,
        checkIsUploadSuccess,
        totalSize,
        totalSizeUnit
    }))
    return (
        <>
            <div className="view">
                <div className="w100 flex-between">
                    <div>
                        <Button type='link' style={{ padding: 0 }} onClick={handleAddFile}>添加文件</Button>
                        <Button type='link' style={{ padding: 0, marginLeft: '10px' }} onClick={handleAddFolder}>添加文件夹</Button>
                    </div>
                    <Button type='link' danger style={{ padding: 0 }} onClick={handleAllDelete}>全部清空</Button>
                </div>
                <div className="file-box mt-6">
                    <LdPrintTable bordered={false} showPage={false} columns={columns.current} rowSelection={false} data={fileList}></LdPrintTable>
                </div>
                <div className="fileInfo flex-between">
                    <span>共{fileList.length}个文件</span>
                    <span>
                        <span style={{ color: sizeColor }}>{totalSize}</span>
                        /{fileLimit}</span>
                </div>
            </div>
        </>
    )
})
export default memo(AddFile)